package com.iweb.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author jay
 * @date 2021/8/7
 * @desc
 */
public class DBHelper {
    private static String url;
    private static String username;
    private static String password;
    private static String driverClassName;

    static {
        init();
    }

    private static void init() {
        Properties prop = new Properties();
        InputStream is = DBHelper.class.getClassLoader().getResourceAsStream("database.properties");
        try {
            prop.load(is);
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
            driverClassName = prop.getProperty("driverClassName");
            // 加载驱动
            Class.forName(driverClassName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {
        // 2.创建连接对象
        Connection connection=DriverManager.getConnection(url, username, password);
        return connection;
    }

    /**
     * 关闭数据库连接
     */
    public static void close(Connection connection) throws Exception {
        if (connection != null) {
            connection.close();
        }
    }

    public static void close(ResultSet rs, Statement st, Connection connection) throws Exception {
        if (rs != null) {
            rs.close();
        }
        if (st != null) {
            st.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}
